<?php
class CategoryModel extends Model{
	public $table='category';
	public $validate=array(
		array('cname','nonull','栏目名称不能为空..',2,3),
		array('unit','nonull','单位不能为空..',2,3),
		array('pricerange','nonull','价格区间不能为空..',2,3),
		array('pid','checkPid',':( PId错误!',2,3),
	);
	//验证PID
	public function checkPid($name,$pid,$msg){
		$pid = intval($pid);
		if($pid===0)return true;
		//根据栏目缓存判断PID是否存在。。。。
		$categoryCache = cache('category');
		if(isset($categoryCache[$pid])){
			return true;
		}else{
			return $msg;
		}
	}
	//添加栏目
	public function addCategory(){
		if($this->create()){
			$insertCid = $this->add();
			if($this->updateCache()){
				return $insertCid;
			}
		}else{
			return false;
		}
	}
	//修改栏目
	public function editCategory(){
		if($this->create()){
			$state = $this->save();
			if($this->updateCache()){
				return $state;
			}
		}else{
			return false;
		}
	}
	//删除栏目
	public function d(){
		$cid=Q('cid',0,'intval');
		$dd=$this->del("cid=$cid");
		if($dd){
			$this->updateCache();
			return true;
		}else{
			$this->error('删除失败');
		}
	}
	//更新缓存
	public function updateCache(){
		$category = $this->getField('cid,cname,pid,unit,pricerange,keywords,description,cattype,gtid');
		// p($category);exit;
		$category = Data::tree($category,'cname');
		if(cache('category',$category)){
			return true;
		}else{
			$this->error='缓存更新失败...';
			return false;
		}
	}

}